package com.liang.pcc.chat;

import com.alibaba.dashscope.common.Message;
import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class MessageHistoryService {

    @Resource
    private StringRedisTemplate messageRedisTemplate;

    // 添加消息到历史记录
    public void addMessage(String sessionId, Message message) {
        String messageJson = JSON.toJSONString(message);
        messageRedisTemplate.opsForList().rightPush("chat:history:" + sessionId, messageJson);
//        redisTemplate.expire("chat:history:" + sessionId, 7, TimeUnit.DAYS);
    }

    // 获取最近N条历史消息
    public List<Message> getRecentMessages(String sessionId, int limit) {
        List<String> messages = messageRedisTemplate.opsForList().range("chat:history:" + sessionId, 0, limit - 1);
        return messages.stream()
                .map(msg -> JSON.parseObject(msg, Message.class))
                .collect(Collectors.toList());
    }

    /**
     * 删除会话内容
     *
     * @param sessionId 会话ID
     */
    public void deleteSession(String sessionId) {
        messageRedisTemplate.delete("chat:history:" + sessionId);
    }
}